import jdk.nashorn.internal.runtime.logging.Logger;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

/**
 * 功能：动态数组
 * 作者：zhoujun
 * 日期： 2025/1/11 23:02
 */
public class DynamicArray implements Iterable<Integer> {




        private int capacity = 8;
        private int size = 0;
        private int[] array = new int[capacity];



        public void insert(int index, int element) {

            checkAndGrow();

            if (index >= 0 && index <= size) {
                System.arraycopy(array, index,
                        array, index + 1, size - index);
            } else {
                System.out.println("数组中无法找到要插入的索引位置");
            }
            array[index] = element;
            size++;
        }

    private void checkAndGrow() {
        if (size == capacity) {
                capacity += capacity >> 1;
                int[] newArray = new int[capacity];
                System.arraycopy(array, 0, newArray, 0, size);
                array = newArray;
        }
    }

    public int get(int index) {
            return array[index];
        }

        public void foreach(Consumer<Integer> consumer) {
            for (int i = 0; i < size; i++) {
               consumer.accept(array[i]);
            }
        }

    public IntStream stream() {
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }

    public int remove(int index) {
        int removed = array[index];
        System.arraycopy(array, index + 1, array, index, size - index - 1);
        size--;
        return removed;
    }


    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;
            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public Integer next() {
                return array[i++];
            }


        };


    }


}